﻿using System;
using Autodesk.Revit.DB;
using YArchitech.Revit;
using YJKCopyModel.QuickModelFrame;
using YJKPresentation.Utils;

namespace YJKCopyModel.ColumnTransModel
{
	[Rebuilder(RebuilderName = "ColumnRebuilder")]
	public class ColumnRebuilder : IRevitModelRebuilder
	{
		public bool TryRebuildRevitModel(Autodesk.Revit.DB.Document inputDoc, RevitModelRequest inputReqeust, out BuildData buildData)
		{
			buildData = new BuildData();
			buildData.NeedResponse = true;
			try
			{
				bool flag = !(inputReqeust is ColumnRevitRequest);
				if (flag)
				{
					return false;
				}
				ColumnRevitRequest columnRevitRequest = inputReqeust as ColumnRevitRequest;
				FamilySymbol thisFamilySybmol = columnRevitRequest.ConfigInfo.ThisFamilySybmol;
				try
				{
					bool flag2 = !thisFamilySybmol.IsActive;
					if (flag2)
					{
						thisFamilySybmol.Activate();
					}
					XYZ pos = columnRevitRequest.LoopInfo.Pos;
					FamilyInstance familyInstance = inputDoc.Create.NewFamilyInstance(pos, thisFamilySybmol, inputDoc.ActiveView.GenLevel, (Autodesk.Revit.DB.Structure.StructuralType)0);
					double topOffset = columnRevitRequest.ConfigInfo.TopOffset;
					bool bSetInsMaterial = columnRevitRequest.ConfigInfo.TypeName == "<程序自选>";
					this.SetFamilyInstanseParameter(inputDoc, familyInstance, topOffset, bSetInsMaterial);
					double rotation = columnRevitRequest.LoopInfo.Rotation;
					ToleranceManger toleranceManger = ToleranceManger.GetToleranceManger();
					double tolerance = toleranceManger.GetTolerance("主体快模-柱：角度公差");
					bool flag3 = Math.Abs(rotation) > tolerance;
					if (flag3)
					{
						Line line = Line.CreateBound(pos, pos + XYZ.BasisZ * 10.0);
						ElementTransformUtils.RotateElement(inputDoc, familyInstance.Id, line, rotation);
					}
					buildData.CreatedElement = familyInstance;
				}
				catch (Exception)
				{
					throw;
				}
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		private void SetFamilyInstanseParameter(Autodesk.Revit.DB.Document doc, FamilyInstance familyIns, double dTopOffset, bool bSetInsMaterial)
		{
			familyIns.GetParameter("顶部偏移").Set(Common.MMToFeet(dTopOffset));
			if (bSetInsMaterial)
			{
				Parameter parameter = familyIns.GetParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM);
				bool flag = parameter != null && !parameter.IsReadOnly;
				if (flag)
				{
					Material materialObject = ColumnManager.GetMaterialObject(doc, ColumnDefaultSet.ColumnMaterialName);
					bool flag2 = materialObject != null;
					if (flag2)
					{
						parameter.Set(materialObject.Id);
					}
				}
			}
		}
	}
}
